<?php
class NotificationsController extends AppController {
	public $uses = array('Meshtiles', 'Notification');
	
	public $notification = array();
	
	public function index() {
		$this->autoRender = false;
		Configure::write('debug', 0);
		
		$uid = $this->Auth->user('uid');
		$timestamp = date('Ymdhis');
		$memcache = new Memcache;
		$memcache->connect("localhost",11211);

		$result = false;
		$try = 0;
		while (!$result && $try <= 1000) {
			$result = $memcache->get($uid);
			
			usleep(20000);
			clearstatcache();
			$try++;
		}
		
		$notice = array();
		
		if ($result) {
			$memcache->delete($uid);
// 			$result = unserialize($result);
// 			foreach ($result as &$rs) {
// 				if ($rs['time'] < $timestamp && $rs['push'] == 0) {
// 					$rs['push'] = 1;
// 					array_push($notice, $rs['msg']);
// 				}
// 			}
// 			$memcache->replace(serialize($result), 0);
// 			echo implode(', ', $notice);
			$result = unserialize($result[0]);
			echo $result['msg'];
		} else {
			echo '';
		}
	}
	
	public function test_write() {
		$uid = $this->Auth->user('uid');
		$memcache = new Memcache;
		$memcache->connect("localhost",11211);
		//$memcache->delete($uid);
		$cache = $memcache->get($uid);
		debug($cache);
		debug($uid);
	}
	
	public function write($uid = null, $msg = null) {
		$this->autoRender = false;
		$uid = $this->Auth->user('uid');
		if ($this->request->is('post') && isset($this->request->data['msg'])) {
			$memcache = new Memcache;
			$memcache->connect("localhost",11211);
			$cache = $memcache->get($uid);
			if (!$cache) {
				$cache = array(array('msg' => $this->request->data['msg'], 'time' => date('YmdHis'), 'push' => 0));
				$memcache->add($uid, serialize($cache), 0);
			} else {
				$cache = unserialize($cache);
				array_push($cache, array('msg' => $this->request->data['msg'], 'time' => date('YmdHis'), 'push' => 0));
				$memcache->replace($uid, serialize($cache), 0);
			}
		}
	}
	
	public function read($uid = null, $timestamp = null) {
		$result = $this->Notification->find('list', array(
			'conditions' => array(
				'uid' => $uid, 
				'push_flg' => 0, 
				'DATE_FORMAT(create, "%Y-%m-%d %H-%i-%s")' < $timestamp
			),
			'recursive' => -1,
			'fields' => array('id', 'message')
		));
		
		return $result ? $result : false;
	}
}